package main.二叉树;

import common.TreeNode;

/**
 * @author tmh
 * @date 2024/9/6 21:08
 * @description
 */
public class T617合并二叉树 {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        //条件判断
        if (root1 == null || root2 == null) {
            return root1 == null ? root2 : root1;
        }
        //进行树的覆盖
        return dfs(root1, root2);
    }

    //中序遍历
    public TreeNode dfs(TreeNode root1, TreeNode root2) {
        if (root1 == null || root2 == null) {
            return root1 == null ? root2 : root1;
        }
        root1.val = root1.val + root2.val;
        //作为root1节点的左节点
        root1.left = dfs(root1.left, root2.left);
        //作为root2节点的右节点
        root1.right = dfs(root1.right, root2.right);
        //因为是把root1去覆盖root2，所以这里返回的是root1
        return root1;
    }
}
